package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.entity.Sku;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.service.SkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author BaiZY on 2020/8/26.
 * @version 1.0
 */
@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {

    /**
     * 根据spuID查询sku的集合
     * @param spuId
     * @return
     */
    @Override
    public List<SkuDTO> querySkuBySpuId(Long spuId) {
        List<Sku> list = query().eq("spu_id", spuId).list();
        return SkuDTO.convertEntityList(list);
    }

    private static final String DEDUCT_STOCK_STATEMENT = "com.leyou.item.mapper.SkuMapper.deductStock";
    private static final String PLUS_STOCK_STATEMENT = "com.leyou.item.mapper.SkuMapper.plusStock";
    @Transactional
    @Override
    public void deductStock(Map<Long, Integer> cartMap) {

        //执行批处理
        executeBatch(sqlSession -> {
            for (Map.Entry<Long, Integer> entry : cartMap.entrySet()) {
                //准备参数
                Map<String,Object> param = new HashMap<>();
                param.put("id", entry.getKey());
                param.put("num",entry.getValue());

                //编译statement,namespace,statementId
                sqlSession.update(DEDUCT_STOCK_STATEMENT, param);
            }
            //刷新
            sqlSession.flushStatements();
        });
    }

    @Transactional
    @Override
    public void plusStock(Map<Long, Integer> cartMap) {
        //批量修改
        executeBatch(sqlSession -> {
            for (Map.Entry<Long, Integer> entry : cartMap.entrySet()) {
                //准备参数
                Map<String,Object> param = new HashMap<>();
                param.put("id", entry.getKey());
                param.put("num", entry.getValue());

                //编译statement,namespace,statement
                sqlSession.update(PLUS_STOCK_STATEMENT,param);
            }
            //刷新
            sqlSession.flushStatements();
        });
    }
}
